package com.lonni.rpc.core.socket.client;

import com.alibaba.fastjson2.JSON;
import com.lonni.rpc.core.commom.RpcMsgType;
import com.lonni.rpc.core.model.RpcResponse;
import com.lonni.rpc.core.socket.codec.RpcProtocol;
import com.lonni.rpc.core.socket.codec.RpcProtocolHeader;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CompletableFuture;

/**
 * 客户端处理程序,用于接收调用响应
 * @author: Lonni
 * @date: 2024/7/9 0009 11:18
 */
@Slf4j
public class RpcClientHandler extends SimpleChannelInboundHandler<RpcProtocol<RpcResponse>> {


    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, RpcProtocol<RpcResponse> protocol) throws Exception {
        log.info("rpcClient--接收到响应:{}", JSON.toJSONString(protocol));
        RpcProtocolHeader header = protocol.getHeader();
        RpcResponse body = protocol.getBody();
        if (header.getMsgType() != (byte) RpcMsgType.RESPONSE.ordinal()) {
            log.error("接收到错误响应");
            throw new RuntimeException("netty client 接收到错误响应");
        }
        CompletableFuture<RpcProtocol<RpcResponse>> future = NettyClientContext.me.getFuture(String.valueOf(header.getRequestId()));
        if (future==null){
            log.error("未找到响应上下文CompletableFuture");
            return;
        }
        future.complete(protocol);
    }

    /**
     * 发生异常,直接关闭
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("client catch exception：", cause);
        cause.printStackTrace();
        ctx.close();
    }
}



